package com.itheima.bigeventt.interceptor;

import com.itheima.bigeventt.utils.JwtUtil;
import com.itheima.bigeventt.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate  redisTemplate;

    List<String> whitelistUrls = Arrays.asList("/user/register", "/api/login"); // 放行的URL列表

    //prehandle：请求到达接口前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查请求的URL是否在白名单内
        String requestURI = request.getRequestURI();
        if (whitelistUrls.contains(requestURI)) {
            return true; // 放行请求
        }
        //token令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            String reto =(String) redisTemplate.opsForValue().get("token");
            if(reto==null){
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal
            ThreadLocalUtil.set(claims);
            //放行
            return true;

        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    //afterCompletion：请求接口结束后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
